package com.Khan.SocialRescueSys.controller.admin;

import com.Khan.SocialRescueSys.pojo.Force;
import com.Khan.SocialRescueSys.pojo.Message;
import com.Khan.SocialRescueSys.pojo.User;
import com.Khan.SocialRescueSys.service.ForceService;
import com.Khan.SocialRescueSys.service.ProvinceService;
import com.Khan.SocialRescueSys.service.SendMail;
import com.Khan.SocialRescueSys.service.TypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Khan Liu
 * @date 2022/4/6 15:04
 */
@Controller
@RequestMapping("/admin")
public class ForceController {

    @Autowired
    private ForceService forceService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private ProvinceService provinceService;

    @Autowired
    SendMail sendMail;

    public void setTypeAndProvince(Model model) {
        model.addAttribute("types", typeService.getAllType());
        model.addAttribute("provinces", provinceService.getAllProvince());
    }

    @GetMapping("/forces")
    public String force(@RequestParam(required = false, defaultValue = "1", value = "pagenum") int pagenum, Model model) {
        PageHelper.startPage(pagenum, 5);
        List<Force> allForce = forceService.getAllForce();
        PageInfo<Force> pageInfo = new PageInfo<>(allForce);
        model.addAttribute("pageInfo", pageInfo);
        setTypeAndProvince(model);
        return "/admin/forces";
    }


    @PostMapping("/forces") //新增、编辑
    public String addEditForce(Force force, HttpSession session, RedirectAttributes attributes) {
        force.setUser((User) session.getAttribute("user"));
        force.setUserId(force.getUser().getId());
        force.setType(typeService.getType(force.getType().getId()));
        force.setTypeId(force.getType().getId());
        force.setProvince(provinceService.getProvince(force.getProvince().getId()));
        force.setProvinceId(force.getProvince().getId());
        force.setUpdateTime(new Date());
        String email = force.getEmail();
        if(!email.contains("@")){
            attributes.addFlashAttribute("msg", "邮件格式错误");
            return "redirect:/admin/forces";
        }else{
            if(email.lastIndexOf("@") > email.lastIndexOf(".")){
                attributes.addFlashAttribute("msg", "邮件格式错误");
                return "redirect:/admin/forces";
            }
        }
        if(force.getId() == null){
            force.setCreateTime(new Date());
            forceService.saveForce(force);

            attributes.addFlashAttribute("msg", "新增成功");
            try{
                sendMail.sendSimpleMail(email,"社会救援力量信息管理统计系统代发","信息审核通过，发布成功。\b请勿回复");
            }catch (Exception e){
                e.printStackTrace();
                attributes.addFlashAttribute("msg","邮件发送失败");
            }
        }else{
            forceService.updateForce(force);
            attributes.addFlashAttribute("msg", "修改成功");
        }

        return "redirect:/admin/forces";
    }

    @GetMapping("/forces/{id}/delete")
    public String deleteForces(@PathVariable Long id, RedirectAttributes attributes){
        forceService.deleteForce(id);
        attributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/admin/forces";
    }

    @GetMapping("/forces/{id}/upload")
    public String uploadForces(@PathVariable Long id, RedirectAttributes attributes){
        forceService.updateForcePublished(id);
        attributes.addFlashAttribute("msg", "发布成功");
        return "redirect:/admin/forces";
    }

    @GetMapping("/forces/input") //去新增博客页面
    public String toAddForce(Model model){
        model.addAttribute("force", new Force());  //返回一个force对象给前端th:object
        setTypeAndProvince(model);
        return "admin/forces-input";
    }

    @GetMapping("/forces/{id}/input") //去编辑博客页面
    public String toEditForce(@PathVariable Long id, Model model){
        Force force = forceService.getForce(id);
        model.addAttribute("force", force);     //返回一个force对象给前端th:object
        setTypeAndProvince(model);
        return "admin/forces-input";
    }

    /**
     * 导出为Excel
     * */
    @RequestMapping(value = "UserExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();//创建HSSFWorkbook对象,  excel的文档对象
        HSSFSheet sheet = workbook.createSheet("信息表"); //excel的表单

//        List<Teacher> classmateList = teacherservice.teacherinfor();
        List<Force> forceList = forceService.getAllForce();

        String fileName = "info-admin"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "标题","发布状态","省份", "邮箱", "电话", "地址","详细内容"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Force force : forceList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(force.getTitle());
            row1.createCell(1).setCellValue(force.isPublished() ? "发布" : "草稿");
            row1.createCell(2).setCellValue(force.getProvince().getName());
            row1.createCell(3).setCellValue(force.getEmail());
            row1.createCell(4).setCellValue(force.getTel());
            row1.createCell(5).setCellValue(force.getAddr());
            row1.createCell(6).setCellValue(force.getContent());
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}
